import classnames from 'classnames'
import { useHistory } from 'react-router'
import { Dialog, NavBar, SearchBar } from 'antd-mobile'

import Icon from '@/components/Icon'
import styles from './index.module.scss'
import { useState } from 'react'
import { useDebounceFn } from 'ahooks'
import { useDispatch, useSelector } from 'react-redux'
import {
  clearHistory,
  getSuggestion,
  setSearchHistories
} from '@/store/actions/search'
import { RootState } from '@/types/store'

const SearchPage = () => {
  const history = useHistory()
  const dispatch = useDispatch()

  const [keyword, setKeyword] = useState('')

  const { suggestion, histories } = useSelector(
    (state: RootState) => state.search
  )
  // console.log(suggestion, histories)

  // // 防抖
  // const timerRef = useRef(-1)

  // // 组价销毁时清理延时器
  // useEffect(() => {
  //   return () => {
  //     clearTimeout(timerRef.current)
  //   }
  // }, [])

  const { run } = useDebounceFn(
    (val: string) => {
      console.log(val)

      dispatch(getSuggestion(val))
    },
    { wait: 500 }
  )

  // 搜索按钮点击
  const onSearch = (text: string) => {
    if (text) {
      dispatch(setSearchHistories(text))

      // 跳转页面
      history.push(`/search/result?keyword=${text}`)
    }
  }

  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={() => history.go(-1)}
        right={
          <span
            className="search-text"
            onClick={() => {
              onSearch(keyword)
            }}
          >
            搜索
          </span>
        }
      >
        <SearchBar
          placeholder="请输入关键字搜索"
          value={keyword}
          onChange={(val) => {
            setKeyword(val)

            run(val)

            // // 清理延时器
            // clearTimeout(timerRef.current)

            // // 创建延时器
            // timerRef.current = window.setTimeout(() => {
            //   console.log(val)
            // }, 500)
          }}
        />
      </NavBar>

      {true && (
        <div
          className="history"
          style={{
            display: !!keyword ? 'none' : 'block'
          }}
        >
          <div className="history-header">
            <span>搜索历史</span>
            <span
              onClick={() => {
                Dialog.confirm({
                  title: '温馨提示',
                  content: '你确定要清空历史记录吗？',
                  onConfirm: () => {
                    dispatch(clearHistory())
                  }
                })
              }}
            >
              <Icon name="iconbtn_del" />
              清除全部
            </span>
          </div>

          <div className="history-list">
            {histories.map((item, index) => (
              <span
                className="history-item"
                key={index}
                onClick={() => onSearch(item)}
              >
                <span className="text-overflow">{item}</span>
                <Icon name="iconbtn_essay_close" />
              </span>
            ))}
          </div>
        </div>
      )}

      <div className={classnames('search-result', !!keyword ? 'show' : '')}>
        {suggestion.map((item, index) => {
          const wrapItem = item?.replace(
            new RegExp(`${keyword}`, 'ig'),
            (match) => {
              return `<span>${match}</span>`
            }
          )
          return (
            <div
              className="result-item"
              key={index}
              onClick={() => onSearch(item)}
            >
              <Icon className="icon-search" name="iconbtn_search" />
              <div
                className="result-value text-overflow"
                dangerouslySetInnerHTML={{ __html: wrapItem }}
              ></div>
            </div>
          )
        })}
      </div>
    </div>
  )
}

export default SearchPage
